#-------------------------------------------------------------------------------
# By Daoyu @2010-07-06 
#-------------------------------------------------------------------------------

from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.template import RequestContext

from uncle.util.page import *
from uncle.project.models import *
from uncle.users.models import *

pre = '/home/b25476/uncle/'
#-------------------------------------------------------------------------------
# Display log in page. 
#-------------------------------------------------------------------------------
def log_in(request):
    if request.GET.has_key('next'):
        return render_to_response('login.html',
            {'next':request.GET['next'],},
            context_instance = RequestContext(request))
    else:
        return render_to_response("login.html", locals());

#-------------------------------------------------------------------------------
# Doing log in. If sucesfull, redirect to.
#-------------------------------------------------------------------------------
def logging(request):
    if request.user.is_authenticated():
        if not request.user.has_perm('users.is_producer'):
            return HttpResponseRedirect('/user/' + str(request.user.id) +'/')
        return HttpResponseRedirect('/user/moods/')
    elif request.method=='POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username = username, password = password)
        if user is not None:
            if user.is_active:
                login(request, user)
                if request.POST.has_key('next'):
                    return HttpResponseRedirect(request.POST['next'])
                if not request.user.has_perm('users.is_producer'):
                    return HttpResponseRedirect('/user/' + str(request.user.id) +'/')
                return HttpResponseRedirect('/user/moods/')
            else:
                pass
        return render_to_response("login.html", locals());
    else:
        return HttpResponseRedirect('/login/')

        

#-------------------------------------------------------------------------------
# Log out. Redirect user to log in page.
#-------------------------------------------------------------------------------
@login_required
def log_out(request):
    logout(request)
    return HttpResponseRedirect('/')
    #return render_to_response("login.html", locals());
    
#-------------------------------------------------------------------------------
# To new a client. Do not need admin to perform. Can only add client.
#-------------------------------------------------------------------------------
def register(request):
    if request.method=='GET':
        form = register_user_form()
        
    elif request.method=='POST':
        form = register_user_form(request.POST)
        if form.is_valid():
            form.save()
            user_temp = User.objects.get(username = form.cleaned_data['username'])
            user_temp.set_password(user_temp.password)
            user_temp.user_permissions.add(
                Permission.objects.get(codename = 'is_client'))
            user_temp.save()
            
            up = User_profile()
            up.user = user_temp;
            up.save()
            
            #request.user.message_set.create(message = 'Add user ' + user_temp.username)
            
            if not request.user.is_authenticated(): 
                return HttpResponseRedirect('/accounts/login/')
            else:
                return HttpResponseRedirect('/user/register/')
    
    return render_to_response('user/register.html',
            {'form':form,  },
            context_instance = RequestContext(request))

def get_all_cat_skill_tool_tag():
    skts = []
    for x in Category.objects.all():
        skt = skill_tool_tag(x)
        [skt.add_tag(y) for y in Tag.objects.filter(category = x)]
        [skt.add_skill(y) for y in Skill.objects.filter(category = x)]
        [skt.add_tool(y) for y in Tool.objects.filter(category = x)]

        skts.append(skt)
    
    return skts

#-------------------------------------------------------------------------------
# Add a new user to UNCLE. Need admin to perform. 
# Can add client, producer, artist. Can also delete user.
#-------------------------------------------------------------------------------
@login_required
def new_user(request):
    skts = get_all_cat_skill_tool_tag()
            
    if request.method == 'GET':        
        form = new_user_form()
        
    elif request.method == 'POST':
        form = new_user_form(request.POST)
        
        if form.is_valid():            
            form.save()
            user_temp = User.objects.get(username = form.cleaned_data['username'])
            user_type = form.cleaned_data['user_type']
            user_temp.set_password(user_temp.password)
            user_temp.user_permissions.add(
                Permission.objects.get(codename = user_type))
                        
            user_temp.save()
            
            if user_type == 'is_artist': # if artit, then prepare the statistic data.
                es = Email_sta()
                es.user =  user_temp
                es.visits = 0
                es.project_counts = 0
                es.save()
                
                les = Last_email_sta()
                les.user = user_temp
                les.visits = 0
                les.project_counts = 0
                les.save()
            
            up = User_profile()
            up.user = user_temp;
            up.role = request.POST['role']
            up.note = request.POST['note']
            up.company = request.POST['company']
            up.address = request.POST['address']
            up.rate = request.POST['rate']
            up.link = request.POST['link']
            up.language = request.POST['language']
            up.phone = request.POST['phone']
            up.office = request.POST['office']
            
            if(request.FILES.has_key('user_photo')):
                from uncle.util.file import upload_and_replace            
                up.photo = "/upload/user/" +upload_and_replace(
                    #'upload/user/', request.FILES['user_photo'] , str(user_temp.id))
                    pre + 'upload/user/', request.FILES['user_photo'] , str(user_temp.id))
                
            if(request.FILES.has_key('user_video')):
                _video = video()
                _video.user = user_temp
                from uncle.util.file import upload
                _f_name = upload('upload/video/' + str(user_temp.id), 
                                 request.FILES['user_video'] , 
                                 pre=pre,
                                 type='.mp4')
                
                f_name = _f_name.split('.')[0]
                
                import os
                os.system('/usr/local/bin/ffmpeg -i ' + pre + _f_name
                          + ' -vcodec libx264 -vpre slow -vpre ipod640 -s 480x360 ' + pre
                          + f_name + '.mp4')            
                
                os.system('/usr/local/bin/ffmpeg -i ' + pre + _f_name +
                        ' ' + pre + f_name +'.jpg')
                
                os.system('rm ' + pre + _f_name)
                
                _video.movie = f_name + '.mp4'
                up.film = _video.movie
                _video.save()
            
            up.save()           
            
            for x in request.POST.getlist('final_skill'):
                su = Skill_user()
                su.user = user_temp
                su.skill = Skill.objects.get(id=x)
                su.save()
            for x in request.POST.getlist('final_tool'):
                tu = Tool_user()
                tu.user = user_temp
                tu.tool = Tool.objects.get(id=x)
                tu.save()
            for x in request.POST.getlist('final_tag'):
                tu = Tag_user()
                tu.user = user_temp
                tu.tag = Tag.objects.get(id=x)
                tu.save()
            
            request.user.message_set.create(message = 'Add user ' + user_temp.username)
            return HttpResponseRedirect('/user/' + str(user_temp.id))

    form_delete = delete_user_form()
    return render_to_response('user/new.html',
        {'form':form, 'form_delete':form_delete, 'skts':skts,},
        context_instance = RequestContext(request))

#-------------------------------------------------------------------------------
# Delete a user from UNCLE.
#-------------------------------------------------------------------------------
@login_required
def delete_user(request):
    if request.method == 'POST':
        u_id = request.POST['user']
        obj = User.objects.get(id = u_id)

        obj.delete()
        request.user.message_set.create(
            message = request.user.username + ' deleted user ' + obj.username)
        return HttpResponseRedirect('/user/new/')

#-------------------------------------------------------------------------------
# Edit user profile. Can only edit own profile.
# Also set the users skills, tools and tags.
#-------------------------------------------------------------------------------
@login_required
def edit_user(request):
#def edit_user(request, p_id):
    pas = Project_artist.objects.all()
#    pas = Project_artist.objects.filter(id = p_id)
    if request.user in [x.artist for x in pas]:
        return HttpResponseRedirect('/403/?msg=You are already in a project and can not edit your profile.')        
    
    if request.method == 'GET': # request to display edit forms
        form = edit_user_form(instance = request.user)
        u_profile = User_profile.objects.filter(user__id = request.user.id)
        _u_e,u_e = User_expire.objects.filter(user__id=request.user.id), User_expire()
        if _u_e:
            u_e = _u_e[0]
        else:
            u_e.user = request.user
            u_e.save()        
        
        img = u_profile[0].photo        
        
        cids, skts,old_tools,old_skills, old_tags= set([]),[],[],[],[];
        if request.user.has_perm('users.is_artist'):
            skts = get_all_cat_skill_tool_tag()            
            for y in Tool_user.objects.filter(user__id=request.user.id):
                old_tools.append(y.tool.id)
                cids.add(y.tool.category.id)
            for x in Skill_user.objects.filter(user__id=request.user.id):
                old_skills.append(x.skill.id)
                cids.add(x.skill.category.id)
            for z in Tag_user.objects.filter(user__id=request.user.id):
                old_tags.append(z.tag.id)
                cids.add(z.tag.category.id)
                
        return render_to_response('user/edit.html',
              {'form':form, 'img':img, 'user_expire':u_e,
               'cids':cids,'skts':skts,'old_tools':old_tools,'old_skills':old_skills,'old_tags':old_tags,},
              context_instance = RequestContext(request))

    elif request.method == 'POST': # data post from edit forms.        
        request.user.first_name = request.POST['first_name']
        request.user.last_name = request.POST['last_name']
        request.user.email = request.POST['email']
        request.user.save()

        u_profile = User_profile.objects.filter(user__id = request.user.id)
        if u_profile: # If user's profile already exist.
            up = u_profile[0]
        else: # Not exist, just new one.
            up = User_profile()
            up.user = request.user
        
        up.role = request.POST['role']        
        up.office = request.POST['office']
        up.phone = request.POST['phone']
        up.language = request.POST['language']
        up.company = request.POST['company']
        up.address = request.POST['address']
        up.rate = request.POST['rate']   
        up.link = request.POST['link']   
        
        u_e = User_expire.objects.get(user__id=request.user.id)
        if request.POST['exp_start'] and request.POST['exp_end']: 
            u_e.start = request.POST['exp_start'] 
            u_e.end = request.POST['exp_end']            
        elif request.POST['exp_start'] and not request.POST['exp_end']:
            u_e.start = request.POST['exp_start']
            u_e.end = None
        elif not request.POST['exp_start'] and request.POST['exp_end']:
            u_e.end = request.POST['exp_end']
            u_e.start = None
        else:
            u_e.start = None
            u_e.end = None
        try:
            u_e.save()
        except:
            request.user.message_set.create(message = 'The time format is wrong!')
            return HttpResponseRedirect('/user/edit/')
        
        if(request.FILES.has_key('photo')): # If a new photo is uploaded            
            from uncle.util.file import upload_and_replace            
            up.photo = '/upload/user/' + upload_and_replace(
                pre + 'upload/user/', request.FILES['photo'] , str(request.user.id))
        
        up.save()
        
        if request.user.has_perm('users.is_artist'):
            update_category_tool_skill(request.user,
                                       [int(x) for x in request.POST.getlist('final_skill')],
                                       [int(x) for x in request.POST.getlist('final_tool')],
                                       [int(x) for x in request.POST.getlist('final_tag')])            
            
        request.user.message_set.create(
            message = 'Profile updated.')
        
        _update = update()
        _update.content = request.user.first_name + ', ' + request.user.last_name + '(' + request.user.username + ') changes profile'    
        _update.save()
             
        return HttpResponseRedirect('/user/edit/')

#-------------------------------------------------------------------------------
# Edit all the users
#-------------------------------------------------------------------------------
@login_required
def edit_all_user(request):
    if request.method=='GET':
        skts = get_all_cat_skill_tool_tag()
        cids,old_tools, old_skills, old_tags = set([]) ,[],[],[]     
        
        artists = User.objects.all()
        cu = request.user # current edit user
        
        if request.user.username!='kth': # test whether the user is in a project.
            pas = Project_artist.objects.filter(artist__id = cu.id)
            if request.user in [x.artist for x in pas]:
                return HttpResponseRedirect('/403/?msg=You are already in a project and can not edit your profile.') 
        
        _u_e,u_e = User_expire.objects.filter(user__id=cu.id), User_expire()

        if _u_e:
            u_e = _u_e[0]
        else:
            u_e.user = cu                
            u_e.save()
        
        if request.user.username=='kth': # if the super user, allow to edit other user.
            if request.GET.has_key('cu'):
                _u = User.objects.filter(id = request.GET['cu'])
                if _u:
                    cu = _u[0]
                    _u_e = User_expire.objects.filter(user__id=_u[0].id)
                    if _u_e:
                        u_e = _u_e[0]
                    else:
                        u_e.user = _u[0]
                        u_e.save()                        
                
        for y in Tool_user.objects.filter(user__id=cu.id):
            old_tools.append(y.tool.id)
            cids.add(y.tool.category.id)
        for x in Skill_user.objects.filter(user__id=cu.id):    
            old_skills.append(x.skill.id)
            cids.add(x.skill.category.id)
        for z in Tag_user.objects.filter(user__id=cu.id):    
            old_tags.append(z.tag.id)
            cids.add(z.tag.category.id)
                
        form = edit_user_form(instance = cu)
        perm = ''
        
        if cu.has_perm('users.is_artist'):
            perm = 'a'
        elif cu.has_perm('users.is_client'):
            perm = 'c'
        
        return render_to_response('user/edit_all.html',
              {'artists':artists,'form':form,'cu':cu,'perm':perm, 'cids':cids, 'user_expire':u_e,
               'skts':skts,'old_tools':old_tools,'old_skills':old_skills,'old_tags':old_tags,},
              context_instance = RequestContext(request))
    elif request.method =='POST':
        _user = User.objects.get(id=request.POST['c_u_id'])
        _user.first_name = request.POST['first_name']
        _user.last_name = request.POST['last_name']
        _user.email = request.POST['email']
            
        _user.save()
        
        u_profile = User_profile.objects.filter(user__id = request.POST['c_u_id'])
        if u_profile: # If user's profile already exist.
            up = u_profile[0]
        else: # Not exist, just new one.
            up = User_profile()
            up.user = _user

        up.email = request.POST['email']
        up.role = request.POST['role']        
        up.office = request.POST['office']
        up.phone = request.POST['phone']
        up.language = request.POST['language']
        up.address = request.POST['address']
        up.company = request.POST['company']
        up.rate = request.POST['rate']
        up.link = request.POST['link']
        
        if(request.FILES.has_key('photo')): # If a new photo is uploaded            
            from uncle.util.file import upload_and_replace            
            up.photo = '/upload/user/' + upload_and_replace(
                #'upload/user/', request.FILES['photo'] , str(request.POST['c_u_id']))
                pre + 'upload/user', request.FILES['photo'] , str(request.POST['c_u_id']))
            
        up.save()
        
        u_e = User_expire.objects.get(user__id=request.POST['c_u_id'])
        if request.POST['exp_start'] and request.POST['exp_end']:                
            u_e.start = request.POST['exp_start'] 
            u_e.end = request.POST['exp_end']
        elif request.POST['exp_start'] and not request.POST['exp_end']:
            u_e.start = request.POST['exp_start']
            u_e.end = None
        elif not request.POST['exp_start'] and request.POST['exp_end']:
            u_e.start = None
            u_e.end = request.POST['exp_end']
        else:
            u_e.start = None
            u_e.end = None
        try:
            u_e.save()            
        except:
            request.user.message_set.create(message = 'The time format is wrong!')
            return HttpResponseRedirect('/user/edit/all/')
        
        update_category_tool_skill(_user,
                                   [int(x) for x in request.POST.getlist('final_skill')],
                                   [int(x) for x in request.POST.getlist('final_tool')],
                                   [int(x) for x in request.POST.getlist('final_tag')]) 
        
        request.user.message_set.create(
            message = 'Profile updated.')

        return HttpResponseRedirect('/user/edit/all/?cu=' + str(request.POST['c_u_id']))
#    else:
#        return HttpResponseRedirect('/user/edit/')

#-------------------------------------------------------------------------------
# Manage of all videos by admin.
#-------------------------------------------------------------------------------
@login_required
def manage_video(request):
    videos = []
    if request.user.username=='kth':
        videos = video.objects.all()
    elif request.user.has_perm('users.is_artist'):
        videos = video.objects.filter(user__id=request.user.id)
        
    _videos = split_into_pages(request, videos)            
    return render_to_response('user/manage_video.html',
        {'videos':_videos, },
        context_instance = RequestContext(request))
    
def edit_video(request, vid):
    _video = video.objects.get(id=vid)
    if (not request.user.has_perm('users.is_producer')) and (not _video.user.id == request.user.id):
        request.user.message_set.create(message = 'You do not have permission to edit this video.')
        return HttpResponseRedirect('/user/assets/')
    if request.method=='GET':
        return render_to_response('user/edit_video.html',
            {'video':_video, },
            context_instance = RequestContext(request))
    else:
        _video.title = request.POST['title']
        _video.text = request.POST['videoText']
        
        _video.save()
        return HttpResponseRedirect('/user/assets/')
    
#-------------------------------------------------------------------------------
# Delete of videos in all video page.
#-------------------------------------------------------------------------------
@login_required   
def delete_video(request, v_id):
    if request.user.has_perm('users.is_producer'):
        video.objects.filter(id=v_id).delete()
        request.user.message_set.create(message = 'Video deleted.')
    else:
        request.user.message_set.create(message = 'You do not have permission to delete video.')
    return HttpResponseRedirect('/user/assets/')

def update_category_tool_skill(user, new_skills, new_tools, new_tags):    
    new_category_tool_skill(user, [y.skill.id for y in Skill_user.objects.filter(user__id=user.id)], new_skills, 0);
    new_category_tool_skill(user, [y.tool.id for y in Tool_user.objects.filter(user__id=user.id)], new_tools, 1);
    new_category_tool_skill(user, [y.tool.id for y in Tag_user.objects.filter(user__id=user.id)], new_tags, 2);    
     
def new_category_tool_skill(user, old, new, type):
    obj_users = [Skill_user, Tool_user, Tag_user]
    for x in set(old) - set(new):
        if type == 0:
            obj_users[type].objects.filter(skill__id=x).delete()
        elif type == 1:
            obj_users[type].objects.filter(tool__id=x).delete()
        elif type == 2:
            obj_users[type].objects.filter(tag__id=x).delete()
    for x in set(new) - set(old):
        su = obj_users[type]()
        su.user = user
        if type == 0:
            su.skill = Skill.objects.get(id=x)
        elif type == 1:
            su.tool = Tool.objects.get(id=x)
        elif type == 2:
            su.tag = Tag.objects.get(id=x)
        su.save()
